/***************************************************************************
*   Copyright (C) 2007 by crackedmind                                     *
*   digital.stream.of.mind@gmail.com                                      *
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU Library General Public License as       *
*   published by the Free Software Foundation; either version 2 of the    *
*   License, or (at your option) any later version.                       *
*                                                                         *
*   This program is distributed in the hope that it will be useful,       *
*   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
*   GNU General Public License for more details.                          *
*                                                                         *
*   You should have received a copy of the GNU Library General Public     *
*   License along with this program; if not, write to the                 *
*   Free Software Foundation, Inc.,                                       *
*   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
***************************************************************************/
#include "precompiled.hpp"
#include "jamfs_log.hpp"

namespace jamfs
{
	const char *levels[] =
	{
		"CRITICAL",
		"ERROR",
		"INFO",
		"DEBUG"
	};

	Logger::~Logger()
	{
		if ( this->is_open() )
			this->close();
	}

	Logger::Logger() : __open(false), __file(NULL), __max_level(1)
	{
	}

	void Logger::open( const char *filename, uint8_t max_level /* = LOG_ERROR */)
	{
		__file = fopen ( filename, "w+" );

		if ( __file != NULL ) {
			__open = true;
			__max_level = max_level;
		}

		fprintf(__file, "%s\t", timestamp().c_str());
		fprintf(__file, "Log started...\n");
	}

	void Logger::close()
	{
		fprintf(__file, "%s\t", timestamp().c_str());
		fprintf(__file, "Log ended...\n");

		if ( __open ) {
			fclose(__file);
			__file = NULL;
		}
	}

	void Logger::log(uint8_t level, const char *fmt, ...)
	{
		if ( level > __max_level )
			return;

		if ( level > LOG_DEBUG )
			level = LOG_DEBUG;

		fprintf(__file, "%s\t(%s) ", timestamp().c_str(), levels[level]);

		va_list vap;

		va_start(vap, fmt);
		vfprintf(__file, fmt, vap);
		va_end(vap);

		fputc('\n', __file);
	}

	std::string Logger::timestamp()
	{
		time_t clock;
		tm* cur_time;
		char timestr[80];

		time(&clock);
		cur_time = localtime(&clock);
		
		strftime(timestr, 80, "%d/%m/%Y %H:%M:%S", cur_time);
		return std::string(timestr);
	}
}